package com.example.service.impl;

import com.example.entity.BuyTicketsInfo;
import com.example.entity.TicketDto;
import com.example.exception.CustomException;
import com.example.mapper.TicketMapper;
import com.example.service.TicketService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class TicketServiceImpl implements TicketService {

    @Autowired
    TicketMapper ticketMapper;

    @Override
    public void add(TicketDto ticketDto) {
        ticketMapper.insert(ticketDto);
    }

    @Override
    public void deleteById(Integer id) {
        ticketMapper.deleteById(id);
    }

    @Override
    public void updateById(TicketDto ticketDto) {
        ticketMapper.updateById(ticketDto);
    }

    @Override
    public PageInfo<TicketDto> selectPage(Integer pageNum, Integer pageSize, String gameName, String gameType) {
        PageHelper.startPage(pageNum,pageSize);
        List<TicketDto> ticketList = ticketMapper.selectAll(gameName,gameType);
        return PageInfo.of(ticketList);
    }
    /**
     * 插入买票记录
     * @param buyTicketsInfo
     */
    @Override
    public void buyTickets(BuyTicketsInfo buyTicketsInfo) {
        //插入购买记录，
        //计算购买时间
        //LocalDateTime  ticketBuyTime = LocalDateTime.now();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        BuyTicketsInfo newBuyTicketsInfo = BuyTicketsInfo.builder()
                .gameId(buyTicketsInfo.getGameId())
                .userId(buyTicketsInfo.getUserId())
                .tickets1(buyTicketsInfo.getTickets1())
                .tickets2(buyTicketsInfo.getTickets2())
                .tickets3(buyTicketsInfo.getTickets3())
                .totalCost(buyTicketsInfo.getTotalCost())
                .ticketBuyTime(timestamp).build();
       ticketMapper.insertBuyTickets(newBuyTicketsInfo);//插入购买记录
        //更新剩余票数
        ticketMapper.updateTickets(buyTicketsInfo);
    }

    @Override
    public PageInfo<BuyTicketsInfo> selectPageTickets(Integer pageNum, Integer pageSize, String gameId, String userId, String userRole, Integer userYonghuId) {
        PageHelper.startPage(pageNum,pageSize);
        //普通用户，自能看到自己的购票记录
        //管理员，可以看到所有用户购票记录，可以根据用户id，赛事id查询购票记录
        if (userRole.equals("普通用户")){
            List<BuyTicketsInfo> ticketList = ticketMapper.selectPageTicketsByUserId(userYonghuId);
            return PageInfo.of(ticketList);
        } else if (userRole.equals("管理员")) {
             List<BuyTicketsInfo> ticketList = ticketMapper.selectPageTickets(gameId,userId);
            return PageInfo.of(ticketList);
        }
        else {

            throw new CustomException("未找到相关购票记录信息！");
        }
    }


}
